<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getUpgradeList"
    :columns="columns"
    row-key="dataManageId"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="dataManage:add"
          >新增</b-button
        >
        <b-button
          icon="delete"
          code="dataManage:remove"
          :disabled="!selectRows.length"
          @click="onDelete()"
          >删除
        </b-button>
      </Space>
    </template>
    <!-- <template #projectTreeSelects="{ record }">
      <Tree
        v-if="record.projectTreeSelects && record.projectTreeSelects.length"
        :tree-data="record.projectTreeSelects"
        :field-names="fileNames"
        style="width: 280px"
      />
    </template> -->
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="onDetail(record)"
        >详情</b-button
      >
      <!-- <b-button
          type="link"
          v-hasPermi="['packageManage:audit']"
          @click="onAudit(record)"
        >
          审核</b-button
        > -->
      <b-button
        icon="remote"
        code="dataPushTotalLog:add"
        type="link"
        @click="handlePush(record)"
        >推送</b-button
      >
      <b-button
        icon="detail"
        type="link"
        code="dataPushTotalLog:query"
        @click="pushRecord(record)"
        >记录</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items">
    <!--   accept='.cer' -->
    <template #upload="{ formState }">
      <Upload
        :before-upload="onBeforeUpload"
        :custom-request="customRequest"
        :show-upload-list="false"
        :max-count="1"
        accept=".mp4,.mkv,.3gp"
        @change="onChange($event, formState)"
      >
        <video
          v-if="videoSourceName"
          :style="`width: ${108 * 4}px; height: ${80 * 3}px;margin: 0 10px;`"
          :src="fileurl"
          controls
          muted
        ></video>
        <div v-else>
          <Button :icon="h(UploadOutlined)">上传视频</Button>
          <p class="mt-2">支持图片格式：mp4,.mkv,.3gp</p>
        </div>
      </Upload>
    </template>
  </FormModal>
  <Modal
    title="推送记录"
    v-model:open="pushRecordVisible"
    :width="1400"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushRecord :page-data="pageDate" @handleCheck="handleCheck" />
  </Modal>
  <Modal
    :title="failTitle"
    v-model:open="pushDeviceVisible"
    :width="1400"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushDevice :page-data="pushDeviceData" />
  </Modal>
  <Modal
    title="推送"
    v-model:open="pushConfigVisible"
    :width="1600"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushConfig
      :page-data="pageDate"
      @pushSuccess="pushSuccess"
      @close="pushConfigVisible = false"
    />
  </Modal>
</template>

<script setup lang="tsx">
import { computed, h, onMounted, ref } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Modal,
  Space,
  TreeProps,
  TreeSelect,
  Upload,
  type UploadChangeParam,
  type UploadProps,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download, hasOwnProperty, listToEnum } from '@/utils/utils';
import {
  auditEnum,
  deviceTypeEnum,
  deviceTypeOption,
  picUseTypeEnum,
} from '@/constant/push';
import { getProjectData } from '@/api/config';
import {
  addData,
  delData,
  getDataListInfo,
  idataManage,
  uploadFile,
} from '@/api/push';
import PushConfig from '../components/PushConfig.vue';
import PushDevice from '../components/PushDevice.vue';
import PushRecord from '../components/PushRecord.vue';

const tableRef = ref();
const pageDate: any = ref({});
const failTitle: any = ref('');
const pushDeviceData: any = ref({});
const pushRecordVisible = ref(false);
const pushDeviceVisible = ref(false);
const deviceListVisible = ref(false);
const pushConfigVisible = ref(false);
const projectData = ref([]);
onMounted(() => {
  getProjectData().then((res: any) => {
    projectData.value = res.data;
    addDisableProperty(projectData.value);
  });
});
const fileNames: TreeProps['fieldNames'] = {
  title: 'label',
};

const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});

const _getUpgradeList = async (params: any) => {
  const res = await getDataListInfo({ ...params, type: '1' });
  return { rows: [...res.rows], total: res.total || 0 };
};
const addDisableProperty = (tree: any) => {
  tree.forEach((item: any) => {
    if (item.type === '1') {
      item.disabled = true;
      item.selectable = false;
    }
    if (item.children) {
      addDisableProperty(item.children);
    }
  });
};
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '编码',
    dataIndex: 'dataCode',
  },

  {
    title: '资料描述',
    dataIndex: 'dataDesc',
    hideInSearch: true,
  },
  {
    title: '发布次数',
    dataIndex: 'publishCount',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    hideInSearch: true,
    dataIndex: 'createBy',
  },
  {
    title: '创建时间',
    width: 150,
    isTime: true,
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 240,
  },
]);
const items = computed<ProFormProps['items']>(() => [
  {
    label: '资料描述',
    type: 'textarea',
    field: 'dataDesc',
    rules: [
      {
        required: true,
        message: '请输入资料描述',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '所属项目',
    type: 'input',
    field: 'projectId',
    rules: [
      {
        required: true,
        message: '请输入所属项目',
        trigger: 'blur',
      },
    ],
    customRender(formState) {
      return (
        <TreeSelect
          v-model:value={formState.projectId}
          fieldNames={{
            children: 'children',
            label: 'label',
            value: 'id',
          }}
          placeholder='请选择'
          allowClear={true}
          treeNodeFilterProp='disabled'
          treeData={projectData.value.map((item) => ({
            // Changed from :treeData to treeData
            ...item,
            disabled: item.type == 1,
          }))}
        />
      );
    },
  },
  {
    label: '视频',
    type: 'input',
    field: 'upload',
    rules: [
      {
        required: true,
        message: '请上传视频',
        trigger: 'blur',
      },
    ],
  },
]);
const { FormModal, open, formRef } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: { labelCol: { span: 4 } },
  // onValuesChange(changeValues, formState) {
  //   if (hasOwnProperty(changeValues, 'deviceType')) {
  //     const { deviceType } = changeValues;
  //     if (deviceType == '3') {
  //       formState.subType = '3';
  //     } else {
  //       formState.subType = '1';
  //     }
  //   }
  // },
});
const getBase64 = (img: Blob, callback: (base64Url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const fileurl = ref('');
const videoHdfsName = ref('');
const videoSourceName = ref('');
const onBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  // const isPng =
  //   file.type === 'video/mp4' ||
  //   file.type === 'image/mkv' ||
  //   file.type === 'image/3gp';
  // if (!isPng) {
  //   message.error('上传仅支持视频格式mp4、mkv、3gp');
  // }
  const isLt5M = file.size / 1024 / 1024 < 500;
  if (!isLt5M) {
    message.error('上传视频大小不能超过500M!');
  }
  return isLt5M;
};
const onChange = (res: any, formState: any) => {
  console.log(res, 'res');
  if (res.file.status === 'done' && res.file.originFileObj) {
    videoSourceName.value = res.file.name;
    getBase64(res.file.originFileObj, (base64Url: string) => {
      fileurl.value = base64Url;
      formState.upload = res;
    });
  }
};

const customRequest: UploadProps['customRequest'] = ({
  file,
  filename,
  onError,
  onSuccess,
  onProgress,
}) => {
  const formData = new FormData();
  formData.append('file', file);
  uploadFile(formData, {
    skipError: true,
    onUploadProgress: onProgress,
  })
    .then((res) => {
      // formRef.value.setFiledValue('publicKey', res.msg);
      videoHdfsName.value = res.data.filename;
      onSuccess?.(res);
    })
    .catch((err) => {
      Modal.error({
        title: '提示',
        centered: true,
        content: err.message,
      });
      onError?.(err);
    });
};
const onAdd = async () => {
  videoSourceName.value = '';
  open({
    title: '新增',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {
      await addData({
        ...params,
        videoSourceName: videoSourceName.value,
        videoHdfsName: videoHdfsName.value,
        type: '1',
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onDetail = async (record: any) => {
  open({
    title: '详情',
    modalType: 'info',
    defaultValue: { ...record },
    hasEditPermission: false,
    serviceApi: () => Promise.resolve(''),
  });
  let response = await idataManage(record);
  videoSourceName.value = record.videoSourceName;
  fileurl.value = 'data:video/mp4;base64,' + response;
};
const onAudit = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认审核通过？`,
    onOk: async () => {
      await packageAudit({ upgradeId: record.upgradeId, isAudit: '0' });
      sleep(() => tableRef.value.refresh());
      message.success('审核成功');
    },
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async () => {
  const dataManageIds = selectRows.value.map((item) => item.dataManageId);
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认删除当前项？`,
    onOk: async () => {
      await delData(dataManageIds.join());
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};

const pushRecord = (record: any) => {
  pageDate.value = record;
  pushRecordVisible.value = true;
};
const handlePush = (record: any) => {
  record.type = 1;
  pageDate.value = record;
  pushConfigVisible.value = true;
};

const handleCheck = (row: any, sta: any) => {
  pushDeviceData.value = row;
  if (sta == '0') {
    pushDeviceData.value.upgradeStatus = sta;
    failTitle.value = '推送失败设备列表';
  } else {
    pushDeviceData.value.upgradeStatus = '';
    failTitle.value = '推送设备列表';
  }
  pushDeviceVisible.value = true;
};
const pushSuccess = (row: any) => {
  sleep(() => tableRef.value.refresh());
  pushConfigVisible.value = false;
  pushDeviceData.value = row;
  failTitle.value = '推送结果';
  pushDeviceVisible.value = true;
};
</script>
